package cn.net.autocode.platform.providers;

import cn.net.autocode.platform.exception.PlatformQueryException;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import cn.net.autocode.platform.providers.service.SaveServ;
import cn.net.autocode.core.bean.ResultT;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("autocode/saveBatchProvider")
public class SaveBatchProviderCtrl extends ProviderCtrl{

    private final SaveServ saveServ;

    public SaveBatchProviderCtrl(SaveServ saveServ) {
        this.saveServ = saveServ;
    }

    @RequestMapping("{tableCode}")
    @Transactional
    public ResultT execute(@PathVariable("tableCode") String tableCode, @RequestBody JSONArray array) throws PlatformQueryException {

        if(array.isEmpty()){
            return ResultT.fail("传入参数为空");
        }
        JSONObject table = this.tableMsg(tableCode);
        String tableName = table.getString("tableName");

        //获取字段的默认值设置
        JSONArray columnsMsg = providerServ.columnsMsg(table.getString("id"));
        //设置自增字段
        JSONArray rules = dictDao.queryJSONArray("select * from ac_table_rules where rule_type in (11,12) and table_id=?", table.getString("id"));

        int arraysize = array.size();
        for(int a=0;a<arraysize;a++){
            JSONObject data = array.getJSONObject(a);
            saveServ.save(data,tableName,columnsMsg,rules);
        }

        return ResultT.success(array);
    }

}
